<?php
// News class


class Register extends Controller {
    var $user_session_id;
    function Register()
    {
        parent::Controller();
	//$this->output->enable_profiler(TRUE);

		//$this->config->load('facebook');
        $this->load->helper(array('form','tiap_helper','html'));
        $this->load->library(array('form_validation','session'));
       // $this->load->model('Directory_company_model');
        // $this->load->library('Session');
       $this->load->model(array('Directory_user_model', 'Settings_model','Directory_services_model',
            'Directory_company_model', 'Directory_photo_model','Directory_invoice_model'));
    }
	
function index(){

                     if($this->input->post('submit'))
		{ 
                        $this->form_validation->set_error_delimiters('<div class="error">','</div>');

                        $this->form_validation->set_rules('name','name','required|trim|xss_clean');
			$this->form_validation->set_rules('company','company','required|trim|xss_clean');
			$this->form_validation->set_rules('telephone','telephone','required|trim|xss_clean');
			$this->form_validation->set_rules('email','email','required|trim|xss_clean|valid_email');

			$this->form_validation->set_message('required', 'Please input %s');

			$this->form_validation->set_message('valid_email', 'Please input valid %s address');

			if ($this->form_validation->run() == TRUE)
			{
			    $data['name'] = $this->input->post('name');
				$data['company'] = $this->input->post('company');
				$data['email'] = $this->input->post('email');
				$data['telephone'] = $this->input->post('telephone');


                $name = $this->input->post('name');
                $company = $this->input->post('company');
                $telephone = $this->input->post('telephone');
                $email = $this->input->post('email');
                redirect('/register/packages/');
                
			}
			else
			{

         $data['name'] =  $name;
        $data['company'] =  $company;
	$data['email'] =  $email;
	$data['telephone'] =  $telephone;

       

         $this->session->set_userdata('name',$this->input->post('name'));
        $this->session->set_userdata('company',$this->input->post('company'));
        $this->session->set_userdata('email',$this->input->post('email'));
	$this->session->set_userdata('telephone',$this->input->post('telephone'));

         $this->session->userdata('name');
                $this->load->view(TEMPLATE_NAME."/front/register/signup",$data);
			}

		} else{
               
                 $this->load->view(TEMPLATE_NAME.'/front/register/signup',$data);
                        }
	}

function packages(){
  $this->load->model('register_model');

  

             if($this->input->post('submit_pack'))
		{
                $this->form_validation->set_error_delimiters('<div class="error">','</div>');
                $this->form_validation->set_rules('package','package','required|trim|xss_clean');
                // $this->form_validation->set_rules('payment_type','payment_type','required|trim|xss_clean');
                $this->form_validation->set_message('required', 'Please input %s');
                    if ($this->form_validation->run() == TRUE)
                    {
                      $package = $this->input->post('package');

                      $this->session->set_userdata('package',$data['package']);
                      redirect('register/rules_and_regulation');
               /* $data['name'] =  $this->session->userdata('name');
		$data['company'] =  $this->session->userdata('company');
		$data['email'] =    $this->session->userdata('email');
		$data['telephone'] =  $this->session->userdata('telephone');
                 $payfor = 'test';
                $country = 'us';
                $amount = '100';

                $data['payment_for'] = $payfor;
                $data['payment_amount'] = $amount;
                 $data['country'] = $country;
                $data['payment_type'] = $this->input->post('payment_type');
                 
               $paymentType = $this->input->post('payment_type');
                        if($paymentType == 1)
                    { 
                    $this->load->view(TEMPLATE_NAME."/front/make_a_payment_creditcard_view",$data);

                    }
                    else
                    { $this->load->model('make_a_payment_model');
                      // $data['bankdetails'] = $this->make_a_payment_model->getBAnkDetails();

                        $arr = array('name' => $name,'companyName' => $company,'telephone' =>$telephone,'email' =>$email,'payfor' =>$payfor,'country' => $country, 'amount' => $amount, 'paymentType' => $paymentType);

                        //$orderid = $this->make_a_payment_model->insertpayment($arr);

                        //$this->make_a_payment_model->sendemailBybanktype($orderid);

                        $this->load->view(TEMPLATE_NAME."/front/make_a_payment_banktransfer_view",$data);

                    }*/

                }else{
                  
                  $this->load->view(TEMPLATE_NAME."/front/register/packages",$data);
                }
             }else{
                 $data['offers'] = $this->register_model->get_package_offers();
                  //print_r($offers);
                  //die();
                 $this->load->view(TEMPLATE_NAME."/front/register/packages",$data);
             }
       
}

function rules_and_regulation()	//for news location step
	{
		
	    $submit_button = $this->input->post('submit_term');
	if($submit_button != ""){
			if($this->session->userdata('step') != '6')
			{
				$this->session->set_userdata('step', 3);
			}

			$this->form_validation->set_rules('agreed', 'agreed','required');
			if($this->form_validation->run() == true) {
                            $agreed = $this->input->post('agreed');
                            if($agreed)
                            redirect('/register/login_information');
			
                        }else{
                        $this->load->view(TEMPLATE_NAME.'/front/register/rules_and_regulation',$data);
                        }
                }else{
                  $this->load->view(TEMPLATE_NAME.'/front/register/rules_and_regulation',$data);
                }
		
		

	}

	function login_information()	//For news story page
	{
               $data = array();
	  //$data['services_list'] = $this->Directory_services_model->get_list_services("services");
      $submit_button = $this->input->post('submit');
      if($submit_button !== "")
      {
        	$form_re_email = $this->input->post('re_email');
        	$form_email = $this->input->post('email');
        	$form_password = $this->input->post('password');
        	//$this->directory_user_email = $this->input->post('email');;
        	//$this->directory_user_password = $this->input->post('password');

           // $this->form_validation->set_rules('recaptcha_response_field', 'Captcha field', 'callback_check_captcha');
         //	$this->form_validation->set_rules('email', 'Email ', 'required|valid_email|callback_check_email');
         	$this->form_validation->set_rules('re_email', 'Email Confirmation', 'required|valid_email|matches[email]');
                $this->form_validation->set_rules('password', 'Password','required|min_length[6]');
                $this->form_validation->set_rules('re_password', 'Password confirmation','required|min_length[6]|matches[password]');
        	if($this->form_validation->run() == TRUE)
            {
                 $directory_user_id = $this->Directory_company_model->register_user($form_email, $form_password);
                 $this->session->set_userdata('new_user_id',$directory_user_id);
                 $this->session_user_id = $directory_user_id;
                 
        	     redirect('register/products/'.$directory_user_id );
        	}

        	$data['form_email'] = $form_email;
        	$data['form_re_email'] = $form_re_email;


      }
      $data['side_left_directory'] = 1;
      $breadcrumb_list = array(
	array('name'=>'Directory', 'href'=>site_url('')),
	array('name'=>'Advertise', 'href'=>site_url('advertise')),
	);
      $data['breadcrumb_list'] = $breadcrumb_list;
      //$data['recaptcha']=$this->recaptcha->get_html();
      $this->load->view(TEMPLATE_NAME.'/front/register/login_information',$data);
	}

   function products()
    { 
      
        $submit_button = $this->input->post('submit');
        if ($submit_button != "")
        { 
            $this->form_validation->set_rules('gender', 'Gender', 'required');
                $this->form_validation->set_rules('category', 'category','required');
                $this->form_validation->set_rules('hair_color', 'Hair color','required');
                $this->form_validation->set_rules('ethnicity', 'Ethnicity','required');
                 $gender = $this->input->post('gender');
            $category = $this->input->post('category');
            $hair_color = $this->input->post('hair_color');
            $ethnicity= $this->input->post('ethnicity');
            $data['gender'] =$gender ;
            $data['category'] = $category ;
            $data['hair_color'] = $hair_color ;
            $data['ethnicity'] =  $ethnicity ;
        	//if($this->form_validation->run() == TRUE)
           // {

          // print_r($data);
            if(!empty ($gender))
            $services = array_merge($gender);
             if(!empty ($category))
            $services = array_merge($category,$services);
             if(!empty ($hair_color))
            $services = array_merge($hair_color,$services);
             if(!empty ($ethnicity))
            $services = array_merge($ethnicity,$services);

           //print_r( $services );
            $this->session->set_userdata('register_products',$services);
            $this->Directory_company_model->update_services($this->session_user_id, $services);
            $data['notification'] = "Services information updated";
           redirect('register/company');
            //}else{
            // $this->load->view(TEMPLATE_NAME . '/front/register/panel_products', $data);
           // }
        }else{
        $data['productType'] = $productType;
        $data['company_detail'] = $company_detail;
        $data['no_breadcrumb'] = 1;
        $data['services_list'] = $this->Directory_services_model->get_list_services("services");
       // print_r($data['services_list']);
         foreach($data['services_list'] as $key=>$value){
               if($value['services']=='Gender')
              { 
                 $gender[]= $value;
              }
              if($value['services']=='Category')
              {
                 $category[]= $value;
              }
              if($value['services']=='Hair Color')
              {
                 $hair_color[]= $value;
              }
              if($value['services']=='Ethnicity')
              {
                 $ethnicity[]= $value;
              }

            }
            $data['gender'] =$gender ;
            $data['category'] = $category ;
            $data['hair_color'] = $hair_color ;
            $data['ethnicity'] =  $ethnicity ;
           // print_r($gender);

        $this->load->view(TEMPLATE_NAME . '/front/register/panel_products', $data);
        }
    }

    function company()
    {       // print_r($this->session->userdata('register_products'));
        $data = array();

        $data['region_list']    = $this->_get_region_by_country(224);

		$data['services_list'] = $this->Directory_services_model->get_list_services("services");

        $submit_button = $this->input->post('submit');
        if ($submit_button != "")
        {
            $this->form_validation->set_rules('name', 'Company name', 'required');
            $this->form_validation->set_rules('description', 'Company Description',
                'required');
            $this->form_validation->set_rules('contact_number', 'Telephone number',
                'required');
            $this->form_validation->set_rules('physical_street', 'Physical street address',
                'required');
            $this->form_validation->set_rules('physical_suburb', 'Physical suburb address',
                'required');
            $this->form_validation->set_rules('physical_city', 'Physical city address',
                'required');

            //$this->form_validation->set_rules('physical_zipcode', 'Zipcode','required');
            $this->form_validation->set_rules('province_id', 'Province', 'required');
            //$this->form_validation->set_rules('city_name', 'City','required');
            $this->form_validation->set_rules('contact_email', 'email address', 'valid_email');
            if ($this->form_validation->run() == true)
            {
               
                if ($this->input->post('website') == 'http://')
                {
                    $company_website = '';
                } else
                {
                    $company_website = substr($this->input->post('website'), 7);
                }
                //$company_website = $this->input->post('website');
                $company_name = $this->input->post('name');
                $company_desc = $this->input->post('description');
                $contact_number = $this->input->post('contact_number');
                $mobile = $this->input->post('mobile_number');
                $fax_number = $this->input->post('fax_number');
                $contact_person = $this->input->post('contact_person');
                //add province name and city name
                $province_id = $this->input->post('province_id');
                $city_name = $this->input->post('city_name');
                $physical_street = $this->input->post('physical_street');
                $physical_suburb = $this->input->post('physical_suburb');
                $physical_city = $this->input->post('physical_city');
                $physical_zipcode = $this->input->post('physical_zipcode');
                $postal_street = $this->input->post('postal_street');
                $postal_suburb = $this->input->post('postal_suburb');
                $postal_city = $this->input->post('postal_city');
                $postal_zipcode = $this->input->post('postal_zipcode');
                $latitude = $this->input->post('latitude');
                $longitude = $this->input->post('longitude');
                $country_name = $this->input->post('country_name');
                $contact_email = $this->input->post('contact_email');
                // -- company logo
                $company_logo = $this->input->post('upload');
                $result = $this->Directory_company_model->update_company($this->session_user_id,
                    ($company_name), $company_desc, $company_website, $contact_number, $mobile,
                    $fax_number, $contact_email, $company_logo, $province_id, $city_name);
                //echo $this->Directory_company_model->db->last_query();
                $this->Directory_company_model->update_location($this->session_user_id, $physical_street,
                    $physical_suburb, $physical_city, $physical_zipcode, $postal_street, $postal_suburb,
                    $postal_city, $postal_zipcode, $latitude, $longitude, $country_name);
                //die($this->Directory_company_model->db->last_query());

                $data['messageBox'] = 'Your changes have been saved';
                redirect('register/payment');

            }
            else
            {
                $data['messageBox'] = 'Your changes failed to saved ' . validation_errors();
                $this->load->view(TEMPLATE_NAME . '/front/register/panel_company_view', $data);

            }
        }


            $company_detail = $this->Directory_company_model->get_company_by_id($this->session_user_id);

        $data['company_detail'] = $company_detail;
       // $data['country_list']   = $this->Location_model->get_country();
        //$data['region_list']    = $this->Location_model->get_region_by_country(224);
        $data['no_breadcrumb']  = 1;
        //echo "<pre><font color='#999999'>";print_r($data); echo "</font></pre>";
        $this->load->view(TEMPLATE_NAME . '/front/register/panel_company_view', $data);
    }

function payment()
    {

        //$this->load->helper('form','url');

        //$this->load->library(array('form_validation','email'));

        //$data = array();

        $this->load->model('make_a_payment_model');

        if(isset($_POST['submit_payment_x']) || isset($_POST['submit_payment']))
		{
          

                $this->_confirmpayemnt();
      

		}
        else
		{
            //$this->load->view(TEMPLATE_NAME."/front/make_a_payment_view",$data);
            redirect('make-a-payment');
        }
    }

    function _confirmpayemnt()
    { //redirect(register/categories);
        $this->load->model('make_a_payment_model');
        $name = $this->input->post('name');
        $company = $this->input->post('company');
        $telephone = $this->input->post('telephone');
        $email = $this->input->post('email');
        $payfor = $this->input->post('payment_for');
        $country = $this->input->post('country');
        $amount = $this->input->post('payment_amount');

        $arr = array('name' => $name,'companyName' => $company,'telephone' =>$telephone,'email' =>$email,'payfor' =>$payfor,'country' => $country, 'amount' => $amount);

        $orderid = $this->make_a_payment_model->insertpayment($arr);

        set_time_limit(100);
        //$paymentType =urlencode( $_POST['paymentType']);
         $firstName =urlencode( $_POST['firstName']);
         $lastName =urlencode( $_POST['lastName']);
         $creditCardType =urlencode( $_POST['creditCardType']);
         $creditCardNumber = urlencode($_POST['creditCardNumber']);
         $expDateMonth =urlencode( $_POST['expDateMonth']);

         $expDateYear =urlencode( $_POST['expDateYear']);
         $cvv2Number = urlencode($_POST['cvv2Number']);
         $budget=$_POST['radio'];

    	if(isset($_POST['radio'])== 1)
   		{

            $budgetperiod=$_POST['budgetPeriod'];
         }
         else
         {
            $budgetperiod="";
         }

         //$URL = "https://www.mygate.co.za/enterprise/3x0x0/ePayService.cfc?wsdl";

        $Mode = "0";
        $MerchantID = "79958a8d-0c7b-4038-8e2e-8948e1d678e1";
        $ApplicationID = "4b775479-a264-444c-b774-22d5521852d8";

        $MerchantRef = "Inv0001";
        $InvTotal = $amount;
        $Currency = "ZAR";

        $CreditCard = $creditCardNumber;
        $CardHolder = $firstName.' '.$lastName;
        $CVC = $cvv2Number;
        $ExpMonth = $expDateMonth;
        $ExpYear = $expDateYear;
        $CardType = $creditCardType;

        //A U T H O R I S E  P U R C H A S E     (A C T I O N  =  1)
        $client = new SoapClient($URL);
        $arrResults = $client->fProcess(
        'fnblive', 			//Gateway
        $MerchantID,  		//MerchantID
        $ApplicationID, 	//ApplicationID
        '1',				//Action
        '',					//TransactionIndex
        'MyGate',			//Terminal
        $Mode,				//Mode
        $MerchantRef,		//MerchantReference
        $InvTotal,			//Amount
        $Currency,			//Currency
        '',					//CashBackAmount
        $CardType,			//CardType
        '',					//AccountType
        $CreditCard,		//CardNumber
        $CardHolder,		//CardHolder
        $CVC,				//CCVNumber
        $ExpMonth,			//ExpiryMonth
        $ExpYear,			//ExpiryYear
        $budget,			//Budget
        $budgetperiod,		//BudgetPeriod
        '',					//AuthorizationNumber
        '',					//PIN
        '',					//DebugMode
        '06',				//eCommerceIndicator
        '',					//verifiedByVisaXID
        '',					//verifiedByVisaCAFF
        '',					//secureCodeUCAF
        '',					//Unique Client Index - this is used to uniquely identify the client and is used by the MyGate Fraud module. It is an optional parameter. Please see online documentation for details.
        '',					//IP Address - this is the IP address of the user using the online gateway (retrieved by yourselves), and is used by the MyGate Fraud module. It is an optional parameter.	 Please see online documentation for details.
        ''					//Shipping Country Code - this is the 2-digit shipping country code of the user, and is used by the MyGate Fraud module. It is an optional parameter. Please see online documentation for details.
        );

        //P U R C H A S E     (A C T I O N  =  3)
        list($ResultName, $ResultValue) = explode("||",$arrResults[0]);
        if ($ResultValue = 0)
        {
        	list($ResultName, $ResultValue) = explode("||",$arrResults[1]);
        	$arrResults = $client->fProcess(
        	'fnblive', 			//Gateway
        	$MerchantID,  		//MerchantID
        	$ApplicationID, 	//ApplicationID
        	'3',				//Action
        	$ResultValue,		//TransactionIndex
        	'',					//Terminal
        	'',					//Mode
        	'',					//MerchantReference
        	'',					//Amount
        	'',					//Currency
        	'',					//CashBackAmount
        	'',					//CardType
        	'',					//AccountType
        	'',					//CardNumber
        	'',					//CardHolder
        	'',					//CCVNumber
        	'',					//ExpiryMonth
        	'',					//ExpiryYear
        	'',					//Budget
        	'',					//BudgetPeriod
        	'',					//AuthorizationNumber
        	'',					//PIN
        	'',					//DebugMode
        	'',					//eCommerceIndicator
        	'',					//verifiedByVisaXID
        	'',					//verifiedByVisaCAFF
        	''					//secureCodeUCAF
        	);
        	list($ResultName, $ResultValue) = explode("||",$arrResults[0]);
        	if ($ResultValue = 0)
        	{

        	$formStr = "<html>";
        	$formStr .="<head>";
        	$formStr .="<title>".'Mykprisguide'."</title>";
        	$formStr .="</head>";
        	$formStr .="<body>";
        	$formStr .="<form name=\"getBackWithDetailsFromPaypal\" id=\"getBackWithDetailsFromPaypal\" method=\"POST\" enctype=\"multipart/form-data\" action=\"".site_url()."make-a-payment/paymentsuccess\">";
        	$formStr .="<input type=\"hidden\" name=\"orderid\" value=\"".$orderid."\"/>";
        	$formStr .="<input type=\"hidden\" name=\"transID\" value=\"".$MerchantID."\" />";
        	$formStr .="<input type=\"hidden\" name=\"transactionType\" value=\"direct\" />";
        	$formStr .="</form>";
        	$formStr .="<script type=\"text/javascript\">document.getElementById('getBackWithDetailsFromPaypal').submit();</script>";
        	$formStr .="</body>";
        	$formStr .="</html>";

        	echo $formStr;

        		//echo("<br />");
        		//echo("Successful Authorization <br />");
        		//list($ResultName, $ResultValue) = explode("||",$arrResults[0]);
        		//echo($ResultValue);
        		//echo("<br />");
        	}
        	else
        	{
        	$formelements .="<head>";
        	$formelements .="<title>Mykprisguide</title>";
        	$formelements .="</head>";
        	$formelements .="<body>";
        	$formelements .="
        				<form name=\"frmfailure\" id=\"frmfailure\" action=\"".site_url()."make-a-payment/paymentfail\" METHOD=\"post\" >
        				<input type=\"hidden\" name=\"firstName\" value='".$_POST['firstName']."' />
        				<input type=\"hidden\" name=\"lastName\" value='".$_POST['lastName']."' />
        				<input type=\"hidden\" name=\"orderid\" value='".$orderid."'/>
        				<input type=\"hidden\" name=\"country\" value='".$_POST['country']."' />
        				<input type=\"hidden\" name=\"city\" value='".$_POST['city']."' />
        				<input type=\"hidden\" name=\"address\" value='".$_POST['address']."' />
        				<input type=\"hidden\" name=\"zip\" value='".$_POST['zip']."' />
        				<input type=\"hidden\" name=\"creditCardType\" value='".$_POST['creditCardType']."' />
        				<input type=\"hidden\" name=\"creditCardNumber\" value='".$_POST['creditCardNumber']."' />
        				<input type=\"hidden\" name=\"expDateMonth\" value='".$_POST['expDateMonth']."' />
        				<input type=\"hidden\" name=\"expDateYear\" value='".$_POST['expDateYear']."' />
        				<input type=\"hidden\" name=\"cvv2Number\" value='".$_POST['cvv2Number']."' />
        				<input type=\"hidden\" name=\"amount\" value='".$_POST['amount']."' />
        				<input type=\"hidden\" name=\"error\" value=\"Failed Authorization\" />
        				</form>
        				";
        				$formelements .="<script type=\"text/javascript\">document.getElementById('frmfailure').submit();</script>";
        	$formelements .="</body>";
        	$formelements .="</html>";
        	echo $formelements;

        	}
        }
        else
        {
        	$formelements .="<head>";
        	$formelements .="<title>Mykprisguide</title>";
        	$formelements .="</head>";
        	$formelements .="<body>";
        	$formelements .="
        				<form name=\"frmfailure\" id=\"frmfailure\" action=\"".site_url()."make-a-payment/paymentfail\" METHOD=\"post\" >
        				<input type=\"hidden\" name=\"firstName\" value='".$_POST['firstName']."' />
        				<input type=\"hidden\" name=\"lastName\" value='".$_POST['lastName']."' />
        				<input type=\"hidden\" name=\"orderid\" value=\"".$orderid."\"/>
        				<input type=\"hidden\" name=\"country\" value='".$_POST['country']."' />
        				<input type=\"hidden\" name=\"city\" value='".$_POST['city']."' />
        				<input type=\"hidden\" name=\"address\" value='".$_POST['address']."' />
        				<input type=\"hidden\" name=\"zip\" value='".$_POST['zip']."' />
        				<input type=\"hidden\" name=\"creditCardType\" value='".$_POST['creditCardType']."' />
        				<input type=\"hidden\" name=\"creditCardNumber\" value='".$_POST['creditCardNumber']."' />
        				<input type=\"hidden\" name=\"expDateMonth\" value='".$_POST['expDateMonth']."' />
        				<input type=\"hidden\" name=\"expDateYear\" value='".$_POST['expDateYear']."' />
        				<input type=\"hidden\" name=\"cvv2Number\" value='".$_POST['cvv2Number']."' />
        				<input type=\"hidden\" name=\"amount\" value='".$_POST['amount']."' />
        				<input type=\"hidden\" name=\"error\" value=\"Failed Authorization\" />
        				</form>
        				";
        				$formelements .="<script type=\"text/javascript\">document.getElementById('frmfailure').submit();</script>";
        	$formelements .="</body>";
        	$formelements .="</html>";
        	echo $formelements;

            }
    }

    function paymentfail()
    {
        $this->load->model('make_a_payment_model');

        $this->make_a_payment_model->deletepaymentfail();

        $this->load->view(TEMPLATE_NAME."/front/make_a_paymentfail_view");
    }

    function paymentsuccess()
    {
        $this->load->model('make_a_payment_model');

        $arr = array('transaction_id ' => $this->input->post('transID'),'pay_status' => '1');

        $cond = array('id' => $this->input->post('orderid'));

        $this->make_a_payment_model->updatepaymentsuccess($arr,$cond);

        $this->make_a_payment_model->sendemailBybanktype($this->input->post('orderid'));

        $this->load->view(TEMPLATE_NAME."/front/make_a_paymentsuccess_view");
    }

    function check_captcha($val)
    {

        $result = $this->recaptcha->check_answer($_SERVER["REMOTE_ADDR"],$this->input->post('recaptcha_challenge_field'),$val);
        if ($result) {
            return true;
        } else {
            $this->form_validation->set_message('check_captcha','Incorrect Security Image Response');
            return false;
        }

    }

    function check_email($val)
    {
        if (!$this->Directory_user_model->check_available_email($val, $this->
            session_user_id))
        {
            $this->form_validation->set_message('check_email', '%s ' . $val .
                ' is already on our system, please use another %s');
            return false;
        } else
        {
            return true;
        }
    }
    function check_ssl()
    {
        if ($_SERVER['HTTPS'] != "on")
        {
            $url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
            header("Location: $url");
            exit;
        }
    }

   function signup_success(){
    	$directory_user_id = $this->uri->segment(3);
    	$directory_user = $this->Directory_user_model->get_detail($directory_user_id);
        $data['user_email'] = $directory_user['email'];
    	$submit_button = $this->input->post('submit');
     	if($submit_button == "resend"){
    		//$this->Directory_company_model->register_user($this->directory_user_email, $this->directory_user_password);
    		$activation_link = $this->Directory_company_model->generate_activation_data($directory_user['email'], $directory_user['password_real']);
    		$this->Directory_company_model->send_activation_email($directory_user['email'], '',$activation_link['link']);
     	}
    	if($submit_button == "update"){
    		$form_email = $this->input->post('email');
    		$this->form_validation->set_rules('email', 'Email ', 'required|valid_email|callback_check_email');
    		if($this->form_validation->run() == TRUE){
    			$this->Directory_user_model->update_email($form_email, $directory_user_id);
    			$activation_link = $this->Directory_company_model->generate_activation_data($directory_user['email'], $directory_user['password_real']);
    			$this->Directory_company_model->send_activation_email($form_email, '',$activation_link['link']);
    			//$this->Directory_company_model->register_user($form_email, $this->directory_user_password);
    		}
     	}
     	$data['directory_user_id'] = $directory_user_id;
     	$breadcrumb_list = array(
			array('name'=>'Directory', 'href'=>site_url('')),
			array('name'=>'Sign Up Success', 'href'=>site_url('signup_success/'.$directory_user_id))
		);

      	$this->load->view(TEMPLATE_NAME.'/front/directory_guest/signup_success', $data);
    }

	function news_photos($id='')		// For news photos
	{
		$this->_check_login();
		$user_session_id = $this->session_user_id;
		$news_id = $this->session->userdata('newsid');
		$photosubmit = $this->input->post('photosubmit');
		$photodelete = $this->input->post('photodelete');
		$photoreplace = $this->input->post('photoreplace');
		$photothumbactive = $this->input->post('photothumbactive');
		$proceed = $this->input->post('proceed');
		if($photosubmit != "")			//News uploading
		{
			$upload = $this->input->post('upload');
			$caption = $this->input->post('imagecaption');
			if($upload)
			{
				for($i=0; $i < count($upload);$i++)
				{

					$data['debug'] .= $this->News_model->insert_news_photos($news_id,$upload[$i],$caption[$i]);
				}
			}
			redirect('/news/news_photos/');
			//$formcount = $this->input->post('formcount');
		}

		if($photodelete != "")	// For deleting photos
		{
			$imageids = $this->input->post('imageid');
			for($i=0;$i < count($imageids); $i++)
			{
				$imagename = $this->News_model->getnewsimage($imageids[$i]);
				$imagename = $imagename[0]['news_image'];
				unlink('uploads/news_photo/'.$imagename);
				unlink('uploads/news_photo/fake/'.$imagename);
				$this->News_model->deletenewsimage($imageids[$i]);
			}
			redirect('/news/news_photos/');
		}

		if($photoreplace != "")	//To replace the photo
		{
			$caption = $this->input->post('imagecaption');
			$imageid = $this->input->post('imageid');
			$prev_image = $this->input->post('prev_image');
			$new_image = $this->input->post('upload');
			if($new_image != "")
			{
				@unlink('uploads/news_photo/'.$prev_image);
				@unlink('uploads/news_photo/fake/'.$prev_image);
				$prev_image = $new_image;
			}
			$this->News_model->update_news_image($imageid,$prev_image,$caption);
			redirect('/news/news_photos/');
		}

		    if($photothumbactive != "")
        {
            $imageid = $this->input->post('imageid');
            $imageid = $imageid[0];
            $this->News_model->reset_news_thumb($news_id);
            $this->News_model->make_thumbnail($news_id,$imageid);
            redirect('/news/news_photos/');
        }

		if($proceed != "")	//Proceed to next step
		{
			$upload = $this->input->post('upload');
			$caption = $this->input->post('imagecaption');
			if($upload)
			{
				for($i=0; $i < count($upload);$i++)
				{
					$data['debug'] .= $this->News_model->insert_news_photos($news_id,$upload[$i],$caption[$i]);
				}
			}

			/*  first uploaded image  as default thumbnail*/
			$getimagelistings = $this->News_model->getallimages($this->session->userdata('newsid'));
			if(!empty($getimagelistings))
			{
			$imageid=$getimagelistings[0]['id'];
			$this->News_model->make_thumbnail($news_id,$imageid);
			}
			if($this->session->userdata('step') != '6')
			{
				$this->session->set_userdata('step', 5);
			}
			redirect('/news/news_keywords/');

		}

		$breadcrumb_list = array(
           array('name'=>'Post News'),
           );
		   $data['breadcrumb_list'] = $breadcrumb_list;

		   if($id != "")
		   {
			   $idlist = array('id' => $id);
			   $data['id'] = $id;
			   $this->load->view(TEMPLATE_NAME.'/front/news/news_edit_photo',$data);
		   } else {
			   $imagecount = $this->News_model->getimagecount($this->session->userdata('newsid'));
			   $data['imagecount'] = $imagecount;
			   $getimagelistings = $this->News_model->getallimages($this->session->userdata('newsid')); //get all images
			   $data['getimagelistings'] = $getimagelistings;
				$this->load->view(TEMPLATE_NAME.'/front/news/news_photos',$data);
		   }

	}

	function news_keywords()	//For news keyword step
	{
		$this->_check_login();
		$user_session_id = $this->session_user_id;
		$news_id = $this->session->userdata('newsid');
		$keywordsubmit = $this->input->post('newkeywords');
		$newstitle = $this->News_model->get_news_title($news_id);
		$newstitle = $newstitle[0]['article_heading'];
		if($keywordsubmit != "")
		{
			if($this->session->userdata('step') != '6')
			{
				$this->session->set_userdata('step', 6);
			}
			$keyword1 = $this->input->post('keyword1');
			$keyword2 = $this->input->post('keyword2');
			$keyword3 = $this->input->post('keyword3');
			$keyword4 = $this->input->post('keyword4');
			$keyword5 = $this->input->post('keyword5');
			$keyword6 = $this->input->post('keyword6');
			$keyword7 = $this->input->post('keyword7');
			$keyword8 = $this->input->post('keyword8');
			$keywords .= $keyword1;
			if($keyword2 != "")
			{
				$keywords .= ", ".$keyword2;
			}
			if($keyword3 != "")
			{
				$keywords .= ", ".$keyword3;
			}
			if($keyword4 != "")
			{
				$keywords .= ", ".$keyword4;
			}
			if($keyword5 != "")
			{
				$keywords .= ", ".$keyword5;
			}
			if($keyword6 != "")
			{
				$keywords .= ", ".$keyword6;
			}
			if($keyword7 != "")
			{
				$keywords .= ", ".$keyword7;
			}
			if($keyword8 != "")
			{
				$keywords .= ", ".$keyword8;
			}
			$this->News_model->insert_news_keywords($news_id,$news_title,$keywords);
			redirect('/news/news_preview/');
		}

		 $breadcrumb_list = array(
           array('name'=>'Post News'),
           );
		   $data['breadcrumb_list'] = $breadcrumb_list;
		   $news_keywords = $this->News_model->get_news_content_forpreview($this->session->userdata('newsid'));
		   $data['news_keywords'] = $news_keywords;
		$this->load->view(TEMPLATE_NAME.'/front/news/news_keywords',$data);

	}

	function news_preview()	//For news preview
	{
		$this->_check_login();
		if($this->session->userdata('newsid') == "")
		{
			redirect('news/');
		}
		$user_session_id = $this->session_user_id;
		$news_id = $this->session->userdata('newsid');
		$newsapprove = $this->input->post('approve');
		if($newsapprove != "")
		{
			$currentdate = date("Y-m-d");
			$currenttime = date("H:i");
			$newsid = $this->input->post('newsid');
			$this->News_model->approve_inserted_news($newsid,$currentdate,$currenttime);
			redirect('news/news_success/'.$newsid);
		}
		 $breadcrumb_list = array(
           array('name'=>'Post News'),
           );
		   $data['breadcrumb_list'] = $breadcrumb_list;
		   $news_content = $this->News_model->get_news_content_forpreview($this->session->userdata('newsid'));
			$user_info = $this->News_model->getuserinfo($news_content[0]['id_user_tiab']);
			$news_photo_info = $this->News_model->getallimages($this->session->userdata('newsid'));
			$data['news_content'] = $news_content;
			$data['user_info'] = $user_info;
			$data['news_photo_info'] = $news_photo_info;
		$this->load->view(TEMPLATE_NAME.'/front/news/news_preview',$data);
	}

	function news_success($newsinsertid = '')	// News success page
	{
		$this->_check_login();
		$user_session_id = $this->session_user_id;
		$this->session->unset_userdata("newsid");
		$this->session->unset_userdata("step");
		$insertednewsid = $newsinsertid;
		$news_content = $this->News_model->get_news_content_forpreview($insertednewsid);
		$articleheading = $news_content[0]['article_heading'];
		$this->session->set_userdata('newsid',"");
		 $breadcrumb_list = array(
           array('name'=>'Post News'),
           );
		   $data['breadcrumb_list'] = $breadcrumb_list;
		   $newsinserted = array('newsinsid' => $insertednewsid);
		   $data['insetedid'] = $news_content[0]['article_number'];
		   $data['articleheading'] = $articleheading;
		   $this->load->view(TEMPLATE_NAME.'/front/news/news_success',$data);
	}

     function _get_region_by_country($country_id){
    $this->db->where('country', '254');
    //$this->db->where('adm1code !=', '');
    $query = $this->db->get('region');
    return $query->result_array();
  }
   }